﻿#include "sourcefile.h"

#include <QTextCodec>
#include <QTextStream>

SourceFile::SourceFile(QString key)
{
    m_key = key;
}

SourceFile::SourceFile(QString key, QString content)
{
    m_key = key;
    m_content = content;
}

SourceFile &SourceFile::replace(QString s_new)
{
    if (m_key.isEmpty() == false)
        m_content.replace(m_key, s_new);
    return *this;
}

SourceFile &SourceFile::replaceUp(QString s_new)
{
    QString upper = m_key.toUpper();
    QString toupper = s_new.toUpper();
    if (upper.isEmpty() == false)
        m_content.replace(upper, toupper);
    return *this;
}

SourceFile &SourceFile::replaceLower(QString s_new)
{
    QString lower = m_key.toLower();
    QString tolower = s_new.toLower();
    if (lower.isEmpty() == false)
        m_content.replace(lower, tolower);
    return *this;
}

SourceFile &SourceFile::replace(QString s_old, QString s_new)
{
    m_content.replace(s_old, s_new);
    return *this;
}

SourceFile &SourceFile::replaceUp(QString s_old, QString s_new)
{
    QString upper = s_old.toUpper();
    QString toupper = s_new.toUpper();
    return replace(upper, toupper);
}

QString &SourceFile::value()
{
    return m_content;
}

void SourceFile::writeToGBK(QFile &file)
{
    QTextStream stream(&file);
    stream.setCodec("GBK");
    stream << m_content;
    stream.flush();
}

void SourceFile::writeToUtf8(QFile &file)
{
    QTextStream stream(&file);
    stream.setCodec("utf-8");
    stream << m_content;
    stream.flush();
}

void SourceFile::writeToUtf8Bom(QFile &file)
{
    QTextStream stream(&file);
    stream.setCodec("utf-8");
    stream.setGenerateByteOrderMark(true); // UTF-8 + Bom
    stream << m_content;
    stream.flush();
}

QString SourceFile::filename(QString ext)
{
    if (ext.startsWith(".")) {
        return QString("%1%2").arg(m_class.toLower()).arg(ext);
    }
    return QString("%1.%2").arg(m_class.toLower()).arg(ext);
}

void SourceFile::setClass(const QString &newClass)
{
    m_class = newClass;
}
